package dk.contix.eclipse.hudson.views;

import java.io.IOException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Display;

import dk.contix.eclipse.hudson.Activator;
import dk.contix.eclipse.hudson.HudsonClient;
import dk.contix.eclipse.hudson.Job;
import dk.contix.eclipse.hudson.ParametersRequiredException;

public final class ScheduleAction extends Action {
	
	private final HudsonView hudsonView;

	public ScheduleAction(HudsonView hudsonView) {
		this.hudsonView = hudsonView;
	}

	@Override
	public void run() {
		IStructuredSelection sel = (IStructuredSelection) hudsonView.viewer.getSelection();
		final Job j = (Job) sel.getFirstElement();

		org.eclipse.core.runtime.jobs.Job sj = new org.eclipse.core.runtime.jobs.Job("Scheduling Hudson build") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				monitor.beginTask("Scheduling job " + j.getName(), 1);
				try {
					final HudsonClient hudsonClient = new HudsonClient();
					try {
						hudsonClient.scheduleJob(j.getName());
					} catch (IOException e1) {
						return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Unable to schedule job", e1);
					} catch (ParametersRequiredException e) {
						Display.getDefault().syncExec(new Runnable() {
							@Override
							public void run() {
								ParameterizedBuildDialog d = new ParameterizedBuildDialog(hudsonClient, j, hudsonView.getSite().getShell(), Activator.getDefault().getPluginPreferences());
								d.open();
								Activator.getDefault().savePluginPreferences();
							}
						});
					}

					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
					}
					hudsonView.refreshAction.run();
				} finally {
					monitor.done();
				}
				return Status.OK_STATUS;
			}

		};
		sj.schedule();
	}
}
